<?php

/*
 Copyright (c) 2005 Kreditor AB
 
 Released under the GNU General Public License
*/


// INCLUDE THE LANGUAGE SUPPORT FILE
if(strpos($_SERVER['SCRIPT_FILENAME'],'admin'))
    @include_once '../'.DIR_WS_CLASSES . 'kreditor_lang.php';
else
    @include_once DIR_WS_CLASSES . 'kreditor_lang.php';


class kreditor
{
    var $code, $title, $description, $enabled;
  
    // class constructor
    function kreditor()
    {
        global $order, $currency;
    
        $this->code = 'kreditor';
        $this->title = MODULE_PAYMENT_KREDITOR_TEXT_TITLE;
        $this->description = MODULE_PAYMENT_KREDITOR_TEXT_DESCRIPTION;
        $this->enabled = ((MODULE_PAYMENT_KREDITOR_STATUS == 'True') ?
            true : false);
    
        if ($currency != "SE" && $currency != "se" && $currency != "SEK" && $currency != "sek")
            $this->enabled = false;

        if ($order->info['total'] > MODULE_PAYMENT_KREDITOR_ORDER_LIMIT)
            $this->enabled = false;

        $this->sort_order = MODULE_PAYMENT_KREDITOR_SORT_ORDER;
    
        if ((int)MODULE_PAYMENT_KREDITOR_ORDER_STATUS_ID > 0)
            $this->order_status = MODULE_PAYMENT_KREDITOR_ORDER_STATUS_ID;

        if (is_object($order))
            $this->update_status();

        $this->form_action_url = tep_href_link(FILENAME_CHECKOUT_PROCESS,
            '', 'SSL', false);
    }
  
    // class methods
    function update_status()
    {
        global $order;
    
        if ($this->enabled == true && (int)MODULE_PAYMENT_KREDITOR_ZONE > 0)
        {
            $check_flag = false;
            $check_query = tep_db_query("select zone_id from " .
                TABLE_ZONES_TO_GEO_ZONES .
                " where geo_zone_id = '" .
                MODULE_PAYMENT_KREDITOR_ZONE .
                "' and zone_country_id = '" .
                $order->billing['country']['id'] .
                "' order by zone_id");

            while ($check = tep_db_fetch_array($check_query))
            {
	            if ($check['zone_id'] < 1)
                {
	                $check_flag = true;
	                break;
	            }
                elseif ($check['zone_id'] == $order->billing['zone_id'])
                {
	                $check_flag = true;
	                break;
	            }
            }
      
            if ($check_flag == false)
	            $this->enabled = false;
        }
    }

    function javascript_validation()
    {
        return false;
    }

    function selection()
    {
        global $order, $customer_id, $currencies, $currency;
    
        $find_personnummer_field_query =
            tep_db_query("show columns from " . TABLE_CUSTOMERS);
    
        $has_personnummer = false;
        $has_dob = false;
    
        while($fields = tep_db_fetch_array($find_personnummer_field_query))
        {
            if ($fields['Field'] == "customers_personnummer")
	            $has_personnummer = true;
            if ($fields['Field'] == "customers_dob")
	            $has_dob = true;
        }
    
        if ($has_personnummer)
        {
            $customer_query = tep_db_query("select customers_personnummer from " .
		         TABLE_CUSTOMERS . " where customers_id = '" . (int)$customer_id."'");
            $customer = tep_db_fetch_array($customer_query);
          
            $personnummer = $customer['customers_personnummer'];
        }
        else if ($has_dob)
        {
            $customer_query = tep_db_query("select customers_dob from " .
		         TABLE_CUSTOMERS . " where customers_id = '" . (int)$customer_id."'");
            $customer = tep_db_fetch_array($customer_query);
          
            $personnummer = substr($customer['customers_dob'],2);
        }
        else
            $personnummer = "";
            
        if (MODULE_PAYMENT_KREDITOR_PRE_POPULATE == "False")
            $personnummer = "";

        // FIX THE LINK TO THE CONDITION
        if(is_numeric(MODULE_KREDITOR_PAYMENT_CHG_FIXED) && MODULE_KREDITOR_PAYMENT_CHG_FIXED >= 0)
            $kreditor_payment_chg = round($currencies->get_value($currency)*MODULE_KREDITOR_PAYMENT_CHG_FIXED, 2);
        else
            $kreditor_payment_chg = 0;
			

            $paymeny_charge_link = "<a href=\"javascript:void();\" onclick=\"window." . 
                "open('https://www.kreditor.se/villkor.yaws?eid=" . 
                MODULE_PAYMENT_KREDITOR_EID."&charge=" . 
                $kreditor_payment_chg."'," . 
                "'villkor','width=300,height=300,scrollbars=no');\">" .
                KREDITOR_LANG_INFO_SE_PAYMENT."</a>";
            
        $fields=array(
            array('title' => KREDITOR_LANG_INFO_SE_IMGINVOICE,
		        'field' => ""),
		    array('title' => KREDITOR_LANG_INFO_SE_CONDITIONS,
			    'field' => "<script type=\"text/javascript\" src=\"http://integration.klarna.com/js/klarnainvoice.js\"></script>
				<script>
					addKlarnaInvoiceEvent(function() { InitKlarnaInvoiceElements('klarna_invoice'," . MODULE_PAYMENT_KREDITOR_EID . ", 'se'," . $kreditor_payment_chg . "); });
				</script>
				<a href=\"#\" id=\"klarna_invoice\" onclick=\"ShowKlarnaInvoicePopup(event);return false;\"></a>"),
		    array('title' => KREDITOR_LANG_INFO_SE_PERSONALNUMBER,
			    'field' => tep_draw_input_field('kreditor_pnum',
                    $personnummer != "" ? strftime("%y%m%d", strtotime($personnummer)) : "")),
		    array('title' => KREDITOR_LANG_INFO_SE_PHONENUMBER,
			    'field' => tep_draw_input_field('kreditor_phone',
                    $order->customer['telephone'])),
		    array('title' => KREDITOR_LANG_INFO_SE_EMAIL,
			    'field' => tep_draw_input_field('kreditor_email',
                    $order->customer['email_address']))); 

        return array('id' => $this->code,
	        'module' => $this->title,
	        'fields' => $fields);
    }
  
  function pre_confirmation_check() {
    require (DIR_WS_CLASSES . 'kreditor.php');
    global $order, $GA_OLD, $KRED_SE_PNO;
    
    $pno = $this->kreditor_pnum = $_POST['kreditor_pnum'];
    $eid = MODULE_PAYMENT_KREDITOR_EID;
    $secret = MODULE_PAYMENT_KREDITOR_SECRET;

    $pnoencoding = $KRED_SE_PNO;
    $type = $GA_OLD;
    
    $status = get_addresses($eid, $pno, $secret, $pnoencoding, $type, $result);
    $this->addrs = $result;
    if ($status != 0){      
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT,
				 'payment_error=kreditor&error='.
				 urlencode($result),
				 'SSL', true, false));
    }
    
    if($result[0][0] == ""){
      $this->kreditor_fname = $result[0][1];
      $this->kreditor_lname = $result[0][0];
    }else{
      $this->kreditor_fname = $result[0][0];
      $this->kreditor_lname = $result[0][1];
    }
    $this->kreditor_street = $result[0][2];
    $this->kreditor_postno = $result[0][3];
    $this->kreditor_city = $result[0][4];
    $order->delivery['firstname'] = $this->kreditor_fname;
    $order->billing['firstname'] = $this->kreditor_fname;
    $order->delivery['lastname'] = $this->kreditor_lname;
    $order->billing['lastname'] = $this->kreditor_lname;
    $order->delivery['street_address'] = $this->kreditor_street;
    $order->billing['street_address'] = $this->kreditor_street;
    $order->delivery['postcode'] = $this->kreditor_postno;
    $order->billing['postcode'] = $this->kreditor_postno;
    $order->delivery['city'] = $this->kreditor_city;
    $order->billing['city'] = $this->kreditor_city;
    $this->kreditor_phone = $_POST['kreditor_phone'];
    $order->delivery['telephone'] = $this->kreditor_phone;
    $order->billing['telephone'] = $this->kreditor_phone;
    $this->kreditor_email = $_POST['kreditor_email'];
    $order->delivery['email_address'] = $this->kreditor_email;
    $order->billing['email_address'] = $this->kreditor_email;
  }
  
  function confirmation() {
    return array('title' => MODULE_PAYMENT_KREDITOR_TEXT_CONFIRM_DESCRIPTION);
  }

  function process_button() {
    global $order, $order_total_modules, $kreditor_ot;
    $counter = 1;
    $a=count($this->addrs);
    $process_button_string = "";
    if($a>1){
      $process_button_string .= "<div align='left'>";
      $process_button_string .=  "<table border='0' width='100%' cellspacing='1' cellpadding='2' class='infoBox'>";
      $process_button_string .=  "<tr><td class='main'><b>".KREDITOR_LANG_INFO_SE_CHOOSEALTERNATIVES."</b></td></tr>";
      $process_button_string .=  "<tr class='infoBoxContents'><td>";
      
      foreach ($this->addrs as $addr){
	$this->kreditor_fname = $addr[0];
	$this->kreditor_lname = $addr[1];
	$this->kreditor_street = $addr[2];
	$this->kreditor_postno = $addr[3];
	$this->kreditor_city = $addr[4];
	
	if($counter == 1){
	  $checked = true;
	}else{
	  $checked = false;
	}
	
	$process_button_string .=
	  tep_draw_radio_field('addr_num', $counter, $checked, '').
	  tep_draw_hidden_field('kreditor_pnum'.$counter,
				$this->kreditor_pnum).
	  tep_draw_hidden_field('kreditor_fname'.$counter,
				$this->kreditor_fname).
	  tep_draw_hidden_field('kreditor_lname'.$counter,
				$this->kreditor_lname).
	  tep_draw_hidden_field('kreditor_street'.$counter,
				$this->kreditor_street).
	  $this->kreditor_street." ".
	  tep_draw_hidden_field('kreditor_postno'.$counter,
				$this->kreditor_postno).
	  $this->kreditor_postno." ".
	  tep_draw_hidden_field('kreditor_city'.$counter,
				$this->kreditor_city).
	  $this->kreditor_city." ".
	  tep_draw_hidden_field('kreditor_phone'.$counter,
				$this->kreditor_phone).
	  tep_draw_hidden_field('kreditor_email'.$counter,
				$this->kreditor_email)."<br/>";
	$counter++;
      }
      $process_button_string .= "</td></tr></table><br/></div>";
    }else{
      $process_button_string .=
	tep_draw_hidden_field('addr_num', $counter, $checked, '').
	tep_draw_hidden_field('kreditor_pnum'.$counter,$this->kreditor_pnum).
	tep_draw_hidden_field('kreditor_fname'.$counter,$this->kreditor_fname).
	tep_draw_hidden_field('kreditor_lname'.$counter,$this->kreditor_lname).
	tep_draw_hidden_field('kreditor_street'.$counter,
			      $this->kreditor_street).
	tep_draw_hidden_field('kreditor_postno'.$counter,
			      $this->kreditor_postno).
	tep_draw_hidden_field('kreditor_city'.$counter,$this->kreditor_city).
	tep_draw_hidden_field('kreditor_phone'.$counter,$this->kreditor_phone).
	tep_draw_hidden_field('kreditor_email'.$counter,$this->kreditor_email);
    }
      
    // This is a bit of a hack. The problem is that we need access to 
    // all additional charges, ie the order_totals list, later in 
    // before_process(), but at that point order_totals->process hasn't
    // been run in that process. We cannot run it ourselves since 
    // checkout_process.php will run it after running before_process.
    // Running it twice causes an error message since the classes
    // will be redefined. 
    // 
    // An alternative to this ugly code is to modify checkout_process.php
    // or order_total.php but we want to avoid that.
    //
    
    $order_totals = $order_total_modules->modules;

    if (is_array($order_totals)) {
      reset($order_totals);
      $j = 0;
      $table = split("[,]", MODULE_PAYMENT_KREDITOR_ORDER_TOTAL_IGNORE);
      
      while (list(, $value) = each($order_totals)) {
	$class = substr($value, 0, strrpos($value, '.'));
	
	if (!$GLOBALS[$class]->enabled){
	  continue;
	}
	$code = $GLOBALS[$class]->code;
	$ignore=false; 
	
	for ($i=0 ; $i<sizeof($table) && $ignore == false ; $i++) {
	  if ($table[$i] == $code){
	    $ignore = true;
	  }
	}
	
	$size = sizeof($GLOBALS[$class]->output);
	
	if ($ignore == false && $size > 0) {
		$kreditor_ot['code_size_'.$j] = $size;
	  for ($i=0; $i<$size; $i++) {
		$kreditor_ot['title_'.$j.'_'.$i] = $GLOBALS[$class]->output[$i]['title'];
		$kreditor_ot['text_'.$j.'_'.$i] = $GLOBALS[$class]->output[$i]['text'];
	    if (is_numeric($GLOBALS[$class]->deduction) &&
		$GLOBALS[$class]->deduction > 0) {
		$kreditor_ot['value_'.$j.'_'.$i] = -$GLOBALS[$class]->deduction;
	    }
	    else {
			$kreditor_ot['value_'.$j.'_'.$i] = $GLOBALS[$class]->output[$i]['value'];
		}
	    
			$kreditor_ot['code_'.$j.'_'.$i] = $GLOBALS[$class]->code;
	  }
	  $j += 1;
	}
      }
	  $kreditor_ot['code_entries'] = $j;
    }
    
	tep_session_register('kreditor_ot');
    
    $process_button_string .= tep_draw_hidden_field(tep_session_name(),
						    tep_session_id());
    return $process_button_string;
  }

  function before_process() {
    global $order, $customer_id, $currency, $currencies,
      $sendto, $billto, $kreditor_ot;

    require (DIR_WS_CLASSES . 'kreditor.php');

    if ($currency != "SE" && $currency != "se" &&
	$currency != "SEK" && $currency != "sek") {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT,
				 'payment_error=kreditor&error=' . KREDITOR_LANG_INFO_SE_ERRORCURRENCY,
				 'SSL', true, false));
      return;
    }

    $eid = MODULE_PAYMENT_KREDITOR_EID;
    $estoreUser = $customer_id;
    $goodsList = array();
    $n = sizeof($order->products);

    // First all the ordinary items
    for ($i = 0 ; $i < $n ; $i++) {
      //    $price_without_tax = ($order->products[$i]['final_price'] * 100/
      //				  (1+$order->products[$i]['tax']/100));
      //
      $price_without_tax = $currencies->get_value($currency) *
	$order->products[$i]['final_price'] * 100;
      $attributes = "";
    
      if(isset($order->products[$i]['attributes'])){
	foreach($order->products[$i]['attributes'] as $attr){
	  $attributes = $attributes . ", " . $attr['option'] . ": " .
	    $attr['value'];
	}
      }

      if (MODULE_PAYMENT_KREDITOR_ARTNO == 'id' ||
	  MODULE_PAYMENT_KREDITOR_ARTNO == '') {
	$goodsList[] =
	  mk_goods($order->products[$i]['qty'],
		   tep_get_prid($order->products[$i]['id']),
		   strip_tags($order->products[$i]['name'] . $attributes),
		   $price_without_tax,
		   $order->products[$i]['tax'],
		   0);
      } else {
	$goodsList[] =
	  mk_goods($order->products[$i]['qty'],
		   $order->products[$i][MODULE_PAYMENT_KREDITOR_ARTNO],
		   strip_tags($order->products[$i]['name'] . $attributes),
		   $price_without_tax,
		   $order->products[$i]['tax'],
		   0);
      }
    }

    // Then the extra charnges like shipping and invoicefee and 
    // discount.

    $extra = $kreditor_ot['code_entries'];
    $tod_rate = tep_get_tax_rate(MODULE_PAYMENT_KREDITOR_TAX_CLASS);
    
    for ($j=0 ; $j<$extra ; $j++) {
      $size = $kreditor_ot["code_size_".$j];
      for ($i=0 ; $i<$size ; $i++) {
	$value = $kreditor_ot["value_".$j."_".$i];
	$name = $kreditor_ot["title_".$j."_".$i];
	$tax = $tod_rate*1;
	$name = rtrim($name, ":");
	if(DISPLAY_PRICE_WITH_TAX == 'true') {
			$price_with_tax = $currencies->get_value($currency) * $value * 100;
	} else {
		$price_with_tax = $currencies->get_value($currency) * $value * 100*(($tax/100)+1);
		}
	if ($value != "" && $value != 0) 
	  $goodsList[] = mk_goods_flags(1, "", $name, $price_with_tax, $tax, 0, 32);
      }
    }

    $secret = MODULE_PAYMENT_KREDITOR_SECRET;
    $estoreOrderNo = "";
    $shipmentfee = 0;
    $shipmenttype = 1;
    $handlingfee = 0;
    $ready_date = "";
	
    // Fixes potential security problem
	
    $addr_num = $_POST['addr_num'];
    $order->delivery['firstname'] = $_POST['kreditor_fname'.$addr_num];
    $order->billing['firstname'] =  $_POST['kreditor_fname'.$addr_num];
    $order->delivery['lastname'] =  $_POST['kreditor_lname'.$addr_num];
    $order->billing['lastname'] =   $_POST['kreditor_lname'.$addr_num];
    $order->delivery['street_address'] =
      $_POST['kreditor_street'.$addr_num];
    $order->billing['street_address'] =
      $_POST['kreditor_street'.$addr_num];
    $order->delivery['postcode'] = $_POST['kreditor_postno'.$addr_num];
    $order->billing['postcode'] = $_POST['kreditor_postno'.$addr_num];
    $order->delivery['city'] = $_POST['kreditor_city'.$addr_num];
    $order->billing['city'] = $_POST['kreditor_city'.$addr_num];
    $order->delivery['telephone'] = $_POST['kreditor_phone'.$addr_num];
    $order->billing['telephone'] = $_POST['kreditor_phone'.$addr_num];
    $order->delivery['email_address'] =
      $_POST['kreditor_email'.$addr_num];
    $order->billing['email_address'] =
      $_POST['kreditor_email'.$addr_num];
    $pno   = $_POST['kreditor_pnum'.$addr_num];
    $fname = $_POST['kreditor_fname'.$addr_num];
    $lname = $_POST['kreditor_lname'.$addr_num];
    $addr = mk_addr_se("", $_POST['kreditor_street'.$addr_num],
		       $_POST['kreditor_postno'.$addr_num],
		       $_POST['kreditor_city'.$addr_num],
		       "",
		       $_POST['kreditor_phone'.$addr_num], 
			 $_POST['kreditor_email'.$addr_num]);
    $passwd = "";
    $clientIp = $_SERVER["REMOTE_ADDR"];
    $newPasswd = "";
    $pno = str_replace("-", "", $pno);
    $pno = str_replace(" ", "", $pno);
	
    if (MODULE_PAYMENT_KREDITOR_AUTO_ACTIVATE == 'True') {
      $flags = $AUTO_ACTIVATE ;
      if (MODULE_PAYMENT_KREDITOR_AUTO_ACTIVATE_SEND_DELAY > 0) {
	$ready_date =
	  date('Y-m-d',
	       strtotime('now +'.
			 MODULE_PAYMENT_KREDITOR_AUTO_ACTIVATE_SEND_DELAY .
			 ' days'));
      }
    } else
      $flags = 0;
    
    $status =
      add_transaction_se($eid, $estoreUser, $secret, $estoreOrderNo,
		     $goodsList, $shipmentfee, $shipmenttype,
		     $handlingfee, $pno, $fname, $lname, $addr,
		     $passwd, $clientIp, $newPasswd, $flags,
		     $comment, $ready_date, "", -1, 0, $result);

    if ($status == 0){

      // insert address in address book to get correct address in
      // confirmation mail (or fetch correct address from address book
      // if it exists)
      
      $q = "select countries_id from " . TABLE_COUNTRIES .
	" where countries_iso_code_2 = 'SE'";

      $check_country_query = tep_db_query($q);
      $check_country = tep_db_fetch_array($check_country_query);

      $cid = $check_country['countries_id'];


      $q = "select address_book_id from " . TABLE_ADDRESS_BOOK .
	" where customers_id = '" . (int)$customer_id .
	"' and entry_firstname = '" . $order->delivery['firstname'] .
	"' and entry_lastname = '" . $order->delivery['lastname'] .
	"' and entry_street_address = '" . $order->delivery['street_address'] .
	"' and entry_postcode = '" . $order->delivery['postcode'] .
	"' and entry_city = '" . $order->delivery['city'] . "'";
      $check_address_query = tep_db_query($q);
      $check_address = tep_db_fetch_array($check_address_query);
      if(is_array($check_address) && count($check_address) > 0){
	$sendto = $billto = $check_address['address_book_id'];
      }else{
	$sql_data_array =
	  array('customers_id' => $customer_id,
		'entry_firstname' => $order->delivery['firstname'],
		'entry_lastname' => $order->delivery['lastname'],
		'entry_street_address' => $order->delivery['street_address'],
		'entry_postcode' => $order->delivery['postcode'],
		'entry_city' => $order->delivery['city'],
		'entry_country_id' => $cid);
	
	tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);
	$sendto = $billto = tep_db_insert_id();
      }

      $order->kreditorref=$result; 
      $payment['tan']=$result;
      
	  tep_session_unregister('kreditor_ot');
      
    } else {
      tep_redirect(tep_href_link(FILENAME_CHECKOUT_PAYMENT,
				 'payment_error=kreditor&error=' .
				 urlencode($result),
				 'SSL', true, false));      
    }
  }
  
  function after_process() {
    global $insert_id, $order;
    
    $find_st_optional_field_query =
      tep_db_query("show columns from " . TABLE_ORDERS);

    $has_kreditor_ref = false;

    while($fields = tep_db_fetch_array($find_st_optional_field_query)){
      if ( $fields['Field'] == "kreditorref" ) 
	$has_kreditor_ref = true;
    }
    
    if ($has_kreditor_ref){
      tep_db_query("update " . TABLE_ORDERS . " set kreditorref='" .
		   $order->kreditorref . "' " . " where orders_id = '" .
		   $insert_id . "'");
    }
      
    // Insert transaction # into history file

    $sql_data_array = array('orders_id' => $insert_id, 
			    'orders_status_id' =>
			    ($order->info['order_status']), 
			    'date_added' => 'now()', 
			    'customer_notified' => 0,
			    'comments' => ('Accepted by Klarna ' .
					   date("Y-m-d G:i:s") .
					   ' Invoice #: ' .
					   $order->kreditorref));

    tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
    $secret = MODULE_PAYMENT_KREDITOR_SECRET;
    $eid = MODULE_PAYMENT_KREDITOR_EID;
    $invno = $order->kreditorref;
    update_orderno($eid, $invno, $secret, utf8_decode($insert_id), $result);
    return false;
    }


  function get_error() {
     
    if (isset($_GET['message']) &&
	strlen($_GET['message']) > 0) {
      $error = stripslashes(urldecode($_GET['message']));
    } else {
      $error = $_GET['error'];
    }
    return array('title' => KREDITOR_LANG_INFO_SE_ERRORINVOICE,
		 'error' => $error);
  }

  function check() {
    if (!isset($this->_check)) {
      $check_query = tep_db_query("select configuration_value from " .
				  TABLE_CONFIGURATION .
				  " where configuration_key = " .
				  "'MODULE_PAYMENT_KREDITOR_STATUS'");
      $this->_check = tep_db_num_rows($check_query);
    }
    return $this->_check;
  }

  function install() {
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Klarna Module', 'MODULE_PAYMENT_KREDITOR_STATUS', 'True', 'Do you want to accept Klarna payments?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_KREDITOR_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'tep_get_zone_class_title', 'tep_cfg_pull_down_zone_classes(', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Merchant ID', 'MODULE_PAYMENT_KREDITOR_EID', '0', 'Merchant ID (estore id) to use for the Klarna service (provided by Klarna)', '6', '0', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Shared secret', 'MODULE_PAYMENT_KREDITOR_SECRET', '', 'Shared secret to use with the Klarna service (provided by Klarna)', '6', '0', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Auto Activate', 'MODULE_PAYMENT_KREDITOR_AUTO_ACTIVATE', 'False', 'Do you want to enable invoice auto activate?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Activate delay (days)', 'MODULE_PAYMENT_KREDITOR_AUTO_ACTIVATE_SEND_DELAY', '0', 'When auto activating delay sending the invoice for x days.', '6', '2', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Product artno attribute (id or model)', 'MODULE_PAYMENT_KREDITOR_ARTNO', 'id', 'Use the following product attribute for ArtNo.', '6', '2', 'tep_cfg_select_option(array(\'id\', \'model\'),', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Pre-populate Personnummer field', 'MODULE_PAYMENT_KREDITOR_PRE_POPULATE', 'False', 'Do you want to pre-populate the personnummer field?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Ignore table', 'MODULE_PAYMENT_KREDITOR_ORDER_TOTAL_IGNORE', 'ot_tax,ot_total,ot_subtotal', 'Ignore these entries from order total list when compiling the invoice data', '6', '2', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Credit limit', 'MODULE_PAYMENT_KREDITOR_ORDER_LIMIT', '10500', 'Only show this payment alternative for orders less than the value below.', '6', '2', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_KREDITOR_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_KREDITOR_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'tep_cfg_pull_down_order_statuses(', 'tep_get_order_status_name', now())");
    
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_PAYMENT_KREDITOR_TAX_CLASS', '0', 'Use the following tax class on the payment charge.', '6', '6', 'tep_get_tax_class_title', 'tep_cfg_pull_down_tax_classes(', now())");
  }
  
  function remove() {
    tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
  }
  
  function keys() {
    return array('MODULE_PAYMENT_KREDITOR_STATUS',
		 'MODULE_PAYMENT_KREDITOR_ORDER_STATUS_ID',
		 'MODULE_PAYMENT_KREDITOR_EID',
		 'MODULE_PAYMENT_KREDITOR_SECRET',
		 'MODULE_PAYMENT_KREDITOR_ARTNO',
		 'MODULE_PAYMENT_KREDITOR_AUTO_ACTIVATE',
		 'MODULE_PAYMENT_KREDITOR_AUTO_ACTIVATE_SEND_DELAY',
		 'MODULE_PAYMENT_KREDITOR_PRE_POPULATE',
		 'MODULE_PAYMENT_KREDITOR_ORDER_LIMIT',
		 'MODULE_PAYMENT_KREDITOR_ORDER_TOTAL_IGNORE',
		 'MODULE_PAYMENT_KREDITOR_ZONE',
		 'MODULE_PAYMENT_KREDITOR_TAX_CLASS',
		 'MODULE_PAYMENT_KREDITOR_SORT_ORDER');
  }
  
}

?>
